package com.example.administrator.wallet.view.activity.mine.Setting;

import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.KeyboardUtils;
import com.example.administrator.wallet.MainActivity;
import com.example.administrator.wallet.R;
import com.example.administrator.wallet.adapter.BackupsGridAdapter;
import com.example.administrator.wallet.utils.AESUtils;
import com.example.administrator.wallet.utils.DimbgUtils;
import com.example.administrator.wallet.utils.ListDataSave;
import com.example.administrator.wallet.utils.SharedPrefsUtil;
import com.example.administrator.wallet.view.activity.PromptActivity;
import com.example.mylibrary.src.main.java.com.quincysx.crypto.utils.Base58;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.example.administrator.wallet.R.id.Linear;
import static com.example.administrator.wallet.R.id.rl_exit_login;
import static com.example.administrator.wallet.utils.DataCleanManager.clearAllCache;
import static com.example.administrator.wallet.utils.DataCleanManager.getTotalCacheSize;


public class SettingActivity extends AppCompatActivity {

    @Bind(R.id.rl_zhujici)
    RelativeLayout rlZhujici;
    @Bind(R.id.rl_BTC)
    RelativeLayout rlBTC;
    @Bind(R.id.rl_ETH)
    RelativeLayout rlETH;
    private ImageButton mIb_back;
    private TextView mV_title, mTv_clear;
    private RelativeLayout mRl_modify_password, mRl_user_protocol, mRl_privacy_policy, mRl_clean_up_caching,rl_Forget_the_trade_password,rl_Modify_the_transaction_password;
    private int FIRST_IN = 1;
    private View view;
    private Button submit;
    private EditText ed1;
    private EditText ed2;
    private EditText ed3;
    private EditText ed4;
    private EditText ed5;
    private EditText ed6;
    private TextView transactionCoin;
    private TextView coin_count;
    private ImageView hidePopup;
    private PopupWindow window;
    private InputMethodManager imm;
    private List<EditText> ed_list = new ArrayList<>();
    private LinearLayout mLinear;
    private List<String> zhujiciList;
    private View inflate;
    private Button but;
    private ImageView hide_img;
    private TextView content;
    private TextView privateKey;
    private GridView mGide;
    private PopupWindow popup;
    private String eth_privateKey;
    private String btc_privateKey;
    private TextView down;
    private String eth;
    private String btc;
    private TextView title;
    private String ether;
    private String btc_coin;
    private String eth_key;
    private String bit_key;
    private String key;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setting);
        ButterKnife.bind(this);
        setStatuColor();

        ether = SharedPrefsUtil.getValue(SettingActivity.this, "wallet", "eth_private", null);
        key = SharedPrefsUtil.getValue(SettingActivity.this, "wallet", "secretKey", null);
//        String password = SharedPrefsUtil.getValue(SettingActivity.this, "wallet", "log", null);
//        byte[] decode = Base58.decode(password);
//        String secretKey = Base64.encode(decode);
        eth_key = AESUtils.decrypt(ether, key);
        Log.e("tag111",eth_key);
        btc_coin = SharedPrefsUtil.getValue(SettingActivity.this, "wallet", "btc_private", null);
        bit_key = AESUtils.decrypt(btc_coin, key);
        Log.e("tag111",btc_coin);
        mIb_back = (ImageButton) findViewById(R.id.finish_img);
        mLinear = (LinearLayout) findViewById(Linear);
        down = (TextView) findViewById(R.id.down);
        mV_title = (TextView) findViewById(R.id.view_title);
        mRl_modify_password = (RelativeLayout) findViewById(R.id.rl_modify_password);
        mRl_user_protocol = (RelativeLayout) findViewById(R.id.rl_user_protocol);
        mRl_privacy_policy = (RelativeLayout) findViewById(R.id.rl_privacy_policy);
        mRl_clean_up_caching = (RelativeLayout) findViewById(R.id.rl_clean_up_caching);
        RelativeLayout LoginOut = (RelativeLayout) findViewById(rl_exit_login);
        RelativeLayout Rl_change = (RelativeLayout) findViewById(R.id.rl_change_la);
        mTv_clear = (TextView) findViewById(R.id.tv_caching);
        rl_Modify_the_transaction_password = (RelativeLayout) findViewById(R.id.rl_Modify_the_transaction_password);//修改交易密码




        //退出登录
        LoginOut.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                //退出若重新注册账户，设置密码重置
                SharedPrefsUtil.putValue(SettingActivity.this, "wallet", "count", FIRST_IN);

                //跳转到特别提示
                ActivityUtils.startActivity(SettingActivity.this, PromptActivity.class);
                onBackPressed();
            }
        });


        mIb_back.setVisibility(View.VISIBLE);
        mV_title.setText(R.string.setted);
        try {
            mTv_clear.setText(getTotalCacheSize(getApplicationContext()));
        } catch (Exception e) {
            e.printStackTrace();
        }

        //修改密码
        mRl_modify_password.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getApplicationContext(), ModifyPasswordActivity.class));
                finish();
                overridePendingTransition(R.anim.next_in_anim, R.anim.next_out_anim);
            }
        });
        rl_Modify_the_transaction_password.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getApplicationContext(), ModifyTransactionPasswordActicity.class));
                finish();
                overridePendingTransition(R.anim.next_in_anim, R.anim.next_out_anim);
            }
        });

        mRl_user_protocol.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getApplicationContext(), UserProtocolActivity.class));
                finish();
                overridePendingTransition(R.anim.next_in_anim, R.anim.next_out_anim);
            }
        });

        mRl_privacy_policy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getApplicationContext(), PrivacyPolicyActivity.class));
                finish();
                overridePendingTransition(R.anim.next_in_anim, R.anim.next_out_anim);
            }
        });

        mRl_clean_up_caching.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                进行清理缓存
                clearAllCache(getApplicationContext());
                try {
                    mTv_clear.setText(getTotalCacheSize(getApplicationContext()));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });


        mIb_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });

        Rl_change.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getApplicationContext(), ChangeLanguageActivity.class));
                overridePendingTransition(R.anim.next_in_anim, R.anim.next_out_anim);
            }
        });

    }

    /**
     * 更改应用语言
     *
     * @param locale
     */
    public void changeAppLanguage(Locale locale) {
        DisplayMetrics metrics = getResources().getDisplayMetrics();
        Configuration configuration = getResources().getConfiguration();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            configuration.setLocale(locale);
        } else {
            configuration.locale = locale;
        }
        getResources().updateConfiguration(configuration, metrics);
        //重新启动Activity
        Intent intent = new Intent(this, MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intent);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finish();
        overridePendingTransition(R.anim.pre_in_anim, R.anim.pre_out_anim);

    }

    public void setStatuColor() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            Window window = getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(getResources().getColor(android.R.color.white));
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }
        setMiuiStatusBarDarkMode(this, true);
        setMiuiStatusBarDarkMode(this, true);
    }

    //设置成白色的背景，字体颜色为黑色。
    public static boolean setMiuiStatusBarDarkMode(Activity activity, boolean darkmode) {
        Class<? extends Window> clazz = activity.getWindow().getClass();
        try {
            int darkModeFlag = 0;
            Class<?> layoutParams = Class.forName("android.view.MiuiWindowManager$LayoutParams");
            Field field = layoutParams.getField("EXTRA_FLAG_STATUS_BAR_DARK_MODE");
            darkModeFlag = field.getInt(layoutParams);
            Method extraFlagField = clazz.getMethod("setExtraFlags", int.class, int.class);
            extraFlagField.invoke(activity.getWindow(), darkmode ? darkModeFlag : 0, darkModeFlag);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @OnClick({R.id.rl_zhujici, R.id.rl_BTC, R.id.rl_ETH})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_zhujici:
                showPopup(0);
                break;
            case R.id.rl_BTC:
                showPopup(1);
                break;
            case R.id.rl_ETH:
                showPopup(2);
                break;
        }
    }

    private void showPopup(final int i) {
        view = View.inflate(this, R.layout.popup_pst, null);
        submit = (Button) view.findViewById(R.id.submit);
        ed1 = (EditText) view.findViewById(R.id.ed1);
        ed2 = (EditText) view.findViewById(R.id.ed2);
        coin_count = (TextView) view.findViewById(R.id.coin_count);
        transactionCoin = (TextView) view.findViewById(R.id.transaction_coin);
        coin_count.setVisibility(View.GONE);
        transactionCoin.setVisibility(View.GONE);
        ed3 = (EditText) view.findViewById(R.id.ed3);
        ed4 = (EditText) view.findViewById(R.id.ed4);
        ed5 = (EditText) view.findViewById(R.id.ed5);
        ed6 = (EditText) view.findViewById(R.id.ed6);
        hidePopup = (ImageView) view.findViewById(R.id.hide_popup);
        ed2.clearFocus();
        ed2.setInputType(InputType.TYPE_NULL);
        ed3.clearFocus();
        ed3.setInputType(InputType.TYPE_NULL);
        ed4.clearFocus();
        ed4.setInputType(InputType.TYPE_NULL);
        ed5.clearFocus();
        ed5.setInputType(InputType.TYPE_NULL);
        ed6.clearFocus();
        ed6.setInputType(InputType.TYPE_NULL);
        window = new PopupWindow(view, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, true);
        window.setFocusable(true);
        window.setTouchable(true);
        window.setOutsideTouchable(true);
        window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        window.showAsDropDown(down, 0, 0);
        popupInputMethodWindow();
        DimbgUtils.dimBackground(SettingActivity.this, 0.5f);
        window.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                DimbgUtils.dimBackground(SettingActivity.this, 1.0f);
                KeyboardUtils.hideSoftInput(SettingActivity.this);
            }
        });

        hidePopup.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                window.dismiss();
            }
        });

        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String log = SharedPrefsUtil.getValue(SettingActivity.this, "wallet", "log", "");
                String s = ed1.getText().toString();
                window.dismiss();
                if (ed6.isSelected() && log.equals(Base58.encode(s.getBytes()))) {
                    imm.hideSoftInputFromWindow(ed1.getWindowToken(), 0);
                    inflate = View.inflate(SettingActivity.this, R.layout.popup_write, null);
                    but = (Button) inflate.findViewById(R.id.submit);
                    hide_img = (ImageView) inflate.findViewById(R.id.hide_popup);
                    content = (TextView) inflate.findViewById(R.id.content);
                    privateKey = (TextView) inflate.findViewById(R.id.privateKey);
                    title = (TextView) inflate.findViewById(R.id.title);
                    mGide = (GridView) inflate.findViewById(R.id.mGide);
                    String copy = getResources().getString(R.string.copy);
                    String know = getString(R.string.know);
                    String copys = getString(R.string.copys);
                    String screenshot = getString(R.string.screenshot);
                    switch (i) {
                        case 0:
                            but.setText(know);
                            title.setText(getString(R.string.zhujici));
                            mGide.setVisibility(View.VISIBLE);
                            content.setText(screenshot);
                            content.setTextColor(getColor(R.color.colorprompt));
                            privateKey.setVisibility(View.GONE);
                            ListDataSave dataSave = new ListDataSave(SettingActivity.this, "wallet");
                            zhujiciList = dataSave.getDataList("zhujici");
                            BackupsGridAdapter adapter = new BackupsGridAdapter(SettingActivity.this, zhujiciList);
                            mGide.setAdapter(adapter);
                            break;
                        case 1:
                            title.setText(getString(R.string.btc_privateKey));
                            but.setText(copys);
                            content.setText(copy);
                            content.setTextColor(getColor(R.color.seekbar));
                            privateKey.setVisibility(View.VISIBLE);
                            privateKey.setText(bit_key);
                            mGide.setVisibility(View.GONE);
                            break;
                        case 2:
                            but.setText(copys);
                            title.setText(getString(R.string.eth_privateKey));
                            content.setText(copy);
                            content.setTextColor(getColor(R.color.seekbar));
                            privateKey.setVisibility(View.VISIBLE);
                            privateKey.setText(eth_key);
                            mGide.setVisibility(View.GONE);
                            break;
                    }
                    popup = new PopupWindow(inflate, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, true);
                    popup.setFocusable(true);
                    popup.setTouchable(true);
                    popup.setOutsideTouchable(true);
                    popup.showAtLocation(mLinear, Gravity.CENTER, 0, 0);

                    hide_img.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            popup.dismiss();
                            DimbgUtils.dimBackground(SettingActivity.this, 1.0f);
                            KeyboardUtils.hideSoftInput(SettingActivity.this);
                        }
                    });
                    if (i == 0) {
                        but.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                popup.dismiss();
                                DimbgUtils.dimBackground(SettingActivity.this, 1.0f);
                                KeyboardUtils.hideSoftInput(SettingActivity.this);
                            }
                        });
                    } else {
                        but.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                copy();
                                popup.dismiss();
                                DimbgUtils.dimBackground(SettingActivity.this, 1.0f);
                                KeyboardUtils.hideSoftInput(SettingActivity.this);
                            }
                        });
                    }

                    DimbgUtils.dimBackground(SettingActivity.this, 0.5f);
                    window.setOnDismissListener(new PopupWindow.OnDismissListener() {
                        @Override
                        public void onDismiss() {
                            DimbgUtils.dimBackground(SettingActivity.this, 1.0f);
                            KeyboardUtils.hideSoftInput(SettingActivity.this);
                        }
                    });

                } else {
                    Toast.makeText(SettingActivity.this, R.string.pst_error, Toast.LENGTH_SHORT).show();
                    showPopup(i);
                }

            }
        });

    }

    private void copy() {
        ClipboardManager clipboard = (ClipboardManager)
                getSystemService(Context.CLIPBOARD_SERVICE);
        CharSequence charSequence = privateKey.getText().toString();
        ClipData clip = ClipData.newPlainText("label", charSequence);
        clipboard.setPrimaryClip(clip);
        Toast.makeText(this, R.string.copy_success, Toast.LENGTH_SHORT).show();
    }


    private void popupInputMethodWindow() {
        new Handler().post(new Runnable() {
            @Override
            public void run() {
                showSoftInputFromWindow(SettingActivity.this);
                ed1.setImeOptions(EditorInfo.IME_ACTION_SEND);
                setEdStatu(ed1);
                initListEd();
            }
        });
    }

    private void initListEd() {
        ed_list.clear();
        ed_list.add(ed1);
        ed_list.add(ed2);
        ed_list.add(ed3);
        ed_list.add(ed4);
        ed_list.add(ed5);
        ed_list.add(ed6);
    }

    private void setEdStatu(final EditText ed) {
        ed.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                if ((ed1.getText().toString().trim()).equals("") || ed1.getText().toString() == null) {
                    initListEd();
                    hideSelected(ed_list);
                } else {
                    switch (ed1.getText().length()) {

                        case 1:
                            initListEd();
                            ed_list.remove(ed1);
                            hideSelected(ed_list);
                            ed1.setSelected(true);
                            break;
                        case 2:
                            initListEd();
                            ed_list.remove(ed1);
                            ed_list.remove(ed2);
                            hideSelected(ed_list);
                            ed2.setSelected(true);
                            ed1.setSelected(true);
                            break;
                        case 3:
                            initListEd();
                            ed_list.remove(ed1);
                            ed_list.remove(ed2);
                            ed_list.remove(ed3);
                            hideSelected(ed_list);
                            ed3.setSelected(true);
                            ed2.setSelected(true);
                            ed1.setSelected(true);
                            break;
                        case 4:
                            initListEd();
                            ed_list.remove(ed1);
                            ed_list.remove(ed2);
                            ed_list.remove(ed3);
                            ed_list.remove(ed4);
                            hideSelected(ed_list);
                            ed4.setSelected(true);
                            ed3.setSelected(true);
                            ed2.setSelected(true);
                            ed1.setSelected(true);
                            break;
                        case 5:
                            initListEd();
                            ed_list.remove(ed1);
                            ed_list.remove(ed2);
                            ed_list.remove(ed3);
                            ed_list.remove(ed4);
                            ed_list.remove(ed5);
                            hideSelected(ed_list);
                            ed5.setSelected(true);
                            ed4.setSelected(true);
                            ed3.setSelected(true);
                            ed2.setSelected(true);
                            ed1.setSelected(true);
                            break;
                        case 6:
                            initListEd();
                            ed_list.remove(ed1);
                            ed_list.remove(ed2);
                            ed_list.remove(ed3);
                            ed_list.remove(ed4);
                            ed_list.remove(ed5);
                            ed_list.remove(ed6);
                            hideSelected(ed_list);
                            ed6.setSelected(true);
                            ed5.setSelected(true);
                            ed4.setSelected(true);
                            ed3.setSelected(true);
                            ed2.setSelected(true);
                            ed1.setSelected(true);
                            break;
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
    }

    public void hideSelected(List<EditText> list_ed) {
        for (int i = 0; i < list_ed.size(); i++) {
            list_ed.get(i).setSelected(false);
        }
    }

    private void showSoftInputFromWindow(SettingActivity settingActivity) {
        ed1.setFocusable(true);
        ed1.setFocusableInTouchMode(true);
        ed1.requestFocus();
        imm = (InputMethodManager) settingActivity.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(ed1, 0);
//        settingActivity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
    }
}
